package cn.gok.oa.file.controller;


import cn.gok.oa.log.LogAnnotation;
import cn.gok.oa.util.ResultData;
import cn.gok.oa.util.UrlUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.extension.api.R;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gok
 * @since 2022-08-04
 */
@RestController
@RequestMapping("/fileMgt")
public class TbFileMgtController {

    @RequestMapping(value = "/fileList",method = RequestMethod.GET)
    @LogAnnotation("获取文件列表")
    public ResultData fileList(String  url, HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        String id = JWT.decode(token).getAudience().get(0);
        List<String> dir = new ArrayList<>();
        List<String> files = new ArrayList<>();
        String path = UrlUtil.getUserDirectoryPath() + File.separator + id + File.separator + url;
        File file = new File(path);
        //判断是否有目录
        if(file.isDirectory()) {
            //获取目录中的所有文件名称
            String[] fileList=file.list();
            //判断文件是否是文件夹，添加到相对应的集合中
            for (String fileName:fileList) {
                File file1 = new File(UrlUtil.getUserDirectoryPath() + File.separator + id + File.separator + url + File.separator + fileName);
                if (file1.isDirectory()){
                    dir.add(fileName);
                }else {
                    files.add(fileName);
                }
            }
            //创建一个集合接收文件夹和非文件夹
            Map<String,Object> data = new HashMap<>();
            data.put("dir",dir);
            data.put("files",files);
            ResultData result = ResultData.success();
            result.setData(data);
            return result;
        }
        return ResultData.fail();
    }

    @RequestMapping(value = "/downLoad",method = RequestMethod.POST)
    @LogAnnotation("文件下载")
    public ResponseEntity<byte[]> downLoad(String  url, HttpServletRequest httpServletRequest){
            String token = httpServletRequest.getHeader("token");
            String id = JWT.decode(token).getAudience().get(0);
            try {
                String[] splitFileName = url.split("/");
                String lastName=splitFileName[splitFileName.length-1];
                String newFileName = new String(lastName.getBytes("UTF-8"), "ISO-8859-1");

                // 文件下载的全路径
                String path = UrlUtil.getUserDirectoryPath() + File.separator + id + File.separator + url;
                // 生成下载的文件
                File file = new File(path);
                // 设置HttpHeaders,使得浏览器响应下载
                HttpHeaders headers = new HttpHeaders();
                // 给浏览器设置下载文件名
                headers.setContentDispositionFormData("attachment", newFileName);
                // 浏览器响应方式
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                // 把文件以二进制格式响应给浏览器
                ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                        headers, HttpStatus.OK);
                return responseEntity;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
    }

    @RequestMapping(value = "/deleteFile",method = RequestMethod.DELETE)
    @LogAnnotation("删除文件")
    public ResultData deleteFile(String url, HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        String id = JWT.decode(token).getAudience().get(0);
        String path = UrlUtil.getUserDirectoryPath() + "/" + id + "/" + url;
        File file =new File(path);
        boolean temp = file.delete();
        if (temp){
            return ResultData.success();
        }
        return ResultData.fail();
    }
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @LogAnnotation("上传文件")
    @ResponseBody
    public ResultData upload(@RequestParam(value="file") MultipartFile file, String url, HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        String id = JWT.decode(token).getAudience().get(0);
        String fileName = file.getOriginalFilename();
        String path = UrlUtil.getUserDirectoryPath() + File.separator + id + File.separator + url;
        File file1 = new File(path+ File.separator+ fileName);
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            ResultData.fail();
        }
        return ResultData.success();
    }
}
